﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace DynamicQuartz.Common
{
 
    public class HttpHelper : IDisposable
    {
        private readonly HttpClient _httpClient;

        public HttpHelper()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30); // 默认超时 30 秒
        }

        public HttpHelper(Action<HttpClient> configureClient)
        {
            _httpClient = new HttpClient();
            configureClient?.Invoke(_httpClient);
        }

        #region GET 请求
        /// <summary>
        /// 异步发送 GET 请求并返回包装结果（字符串）
        /// </summary>
        public async Task<HttpResponse<string>> GetAsync(string url)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                string content = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    return HttpResponse<string>.Success((int)response.StatusCode, content);
                }
                return HttpResponse<string>.Fail((int)response.StatusCode, $"请求失败: {content}");
            }
            catch (Exception ex)
            {
                return HttpResponse<string>.Fail(0, $"GET 请求异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步发送 GET 请求并返回包装结果（字符串）
        /// </summary>
        public HttpResponse<string> Get(string url)
        {
            return GetAsync(url).GetAwaiter().GetResult();
        }

        /// <summary>
        /// 异步发送 GET 请求并反序列化为指定类型
        /// </summary>
        public async Task<HttpResponse<T>> GetAsync<T>(string url)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                string content = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    T data = JsonSerializer.Deserialize<T>(content);
                    return HttpResponse<T>.Success((int)response.StatusCode, data);
                }
                return HttpResponse<T>.Fail((int)response.StatusCode, $"请求失败: {content}");
            }
            catch (Exception ex)
            {
                return HttpResponse<T>.Fail(0, $"GET 请求异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步发送 GET 请求并反序列化为指定类型
        /// </summary>
        public HttpResponse<T> Get<T>(string url)
        {
            return GetAsync<T>(url).GetAwaiter().GetResult();
        }
        #endregion

        #region POST 请求
        /// <summary>
        /// 异步发送 POST 请求（表单格式）
        /// </summary>
        public async Task<HttpResponse<string>> PostFormAsync(string url, Dictionary<string, string> formData)
        {
            try
            {
                var content = new FormUrlEncodedContent(formData);
                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                string result = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    return HttpResponse<string>.Success((int)response.StatusCode, result);
                }
                return HttpResponse<string>.Fail((int)response.StatusCode, $"请求失败: {result}");
            }
            catch (Exception ex)
            {
                return HttpResponse<string>.Fail(0, $"POST 表单请求异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步发送 POST 请求（表单格式）
        /// </summary>
        public HttpResponse<string> PostForm(string url, Dictionary<string, string> formData)
        {
            return PostFormAsync(url, formData).GetAwaiter().GetResult();
        }

        /// <summary>
        /// 异步发送 POST 请求（JSON 格式）
        /// </summary>
        public async Task<HttpResponse<string>> PostJsonAsync(string url, object data)
        {
            try
            {
                string json = JsonSerializer.Serialize(data);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                string result = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    return HttpResponse<string>.Success((int)response.StatusCode, result);
                }
                return HttpResponse<string>.Fail((int)response.StatusCode, $"请求失败: {result}");
            }
            catch (Exception ex)
            {
                return HttpResponse<string>.Fail(0, $"POST JSON 请求异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步发送 POST 请求（JSON 格式）
        /// </summary>
        public HttpResponse<string> PostJson(string url, object data)
        {
            return PostJsonAsync(url, data).GetAwaiter().GetResult();
        }

        /// <summary>
        /// 异步发送 POST 请求（JSON 格式）并反序列化结果
        /// </summary>
        public async Task<HttpResponse<T>> PostJsonAsync<T>(string url, object data)
        {
            try
            {
                string json = JsonSerializer.Serialize(data);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                string result = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    T deserializedData = JsonSerializer.Deserialize<T>(result);
                    return HttpResponse<T>.Success((int)response.StatusCode, deserializedData);
                }
                return HttpResponse<T>.Fail((int)response.StatusCode, $"请求失败: {result}");
            }
            catch (Exception ex)
            {
                return HttpResponse<T>.Fail(0, $"POST JSON 请求异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步发送 POST 请求（JSON 格式）并反序列化结果
        /// </summary>
        public HttpResponse<T> PostJson<T>(string url, object data)
        {
            return PostJsonAsync<T>(url, data).GetAwaiter().GetResult();
        }
        #endregion

        #region PUT 请求
        /// <summary>
        /// 异步发送 PUT 请求（JSON 格式）
        /// </summary>
        public async Task<HttpResponse<string>> PutJsonAsync(string url, object data)
        {
            try
            {
                string json = JsonSerializer.Serialize(data);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PutAsync(url, content);
                string result = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    return HttpResponse<string>.Success((int)response.StatusCode, result);
                }
                return HttpResponse<string>.Fail((int)response.StatusCode, $"请求失败: {result}");
            }
            catch (Exception ex)
            {
                return HttpResponse<string>.Fail(0, $"PUT 请求异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步发送 PUT 请求（JSON 格式）
        /// </summary>
        public HttpResponse<string> PutJson(string url, object data)
        {
            return PutJsonAsync(url, data).GetAwaiter().GetResult();
        }
        #endregion

        #region DELETE 请求
        /// <summary>
        /// 异步发送 DELETE 请求
        /// </summary>
        public async Task<HttpResponse<string>> DeleteAsync(string url)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.DeleteAsync(url);
                string result = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    return HttpResponse<string>.Success((int)response.StatusCode, result);
                }
                return HttpResponse<string>.Fail((int)response.StatusCode, $"请求失败: {result}");
            }
            catch (Exception ex)
            {
                return HttpResponse<string>.Fail(0, $"DELETE 请求异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步发送 DELETE 请求
        /// </summary>
        public HttpResponse<string> Delete(string url)
        {
            return DeleteAsync(url).GetAwaiter().GetResult();
        }
        #endregion

        #region 自定义请求头
        /// <summary>
        /// 设置请求头
        /// </summary>
        public void SetHeaders(Dictionary<string, string> headers)
        {
            _httpClient.DefaultRequestHeaders.Clear();
            foreach (var header in headers)
            {
                _httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
        }
        #endregion

        #region 释放资源
        /// <summary>
        /// 释放 HttpClient 资源
        /// </summary>
        public void Dispose()
        {
            _httpClient?.Dispose();
        }
        #endregion
    }

    public class HttpResponse<T>
    {
        /// <summary>
        /// 是否成功（状态码 2xx）
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// HTTP 状态码
        /// </summary>
        public int StatusCode { get; set; }

        /// <summary>
        /// 消息（成功或错误信息）
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 返回的数据（反序列化后的结果）
        /// </summary>
        public T Data { get; set; }

        // 构造函数
        public HttpResponse(bool isSuccess, int statusCode, string message, T data)
        {
            IsSuccess = isSuccess;
            StatusCode = statusCode;
            Message = message;
            Data = data;
        }

        // 静态方法：成功响应
        public static HttpResponse<T> Success(int statusCode, T data, string message = "请求成功")
        {
            return new HttpResponse<T>(true, statusCode, message, data);
        }

        // 静态方法：失败响应
        public static HttpResponse<T> Fail(int statusCode, string message, T data = default)
        {
            return new HttpResponse<T>(false, statusCode, message, data);
        }
    }
}
